package com.yhsoft.sys.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yhsoft.common.response.PageResult;
import com.yhsoft.common.vo.Result;
import com.yhsoft.sys.controller.Response.NoticeDetailOutVo;
import com.yhsoft.sys.controller.Response.NoticeListOutVo;
import com.yhsoft.sys.controller.request.AddNoticeInVo;
import com.yhsoft.sys.controller.request.EditNoticeInVo;
import com.yhsoft.sys.controller.request.NoticeListInVo;
import com.yhsoft.sys.entity.Notice;
import com.yhsoft.sys.service.INoticeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

/**
 * <p>
 * 公告信息表 前端控制器
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-11-20
 */
@Api(tags = {"N-公告相关接口"})
@RestController
@RequestMapping("/sys/notice")
public class NoticeController {
    @Autowired
    private INoticeService iNoticeService;

    @ApiOperation("新增公告")
    @PostMapping("/add")
    public Result<?> add(@Valid @RequestBody AddNoticeInVo inVo){
        String msg = iNoticeService.add(inVo);
        return Result.success(msg);
    }

    @ApiOperation("删除公告")
    @DeleteMapping("/deleteNotice")
    public Result<?> deleteNotice(@NotNull(message = "公告id不能为空") @RequestParam Integer id) {
        iNoticeService.getBaseMapper().deleteById(id);
        return Result.success("删除成功！");
    }

    @ApiOperation("编辑公告(会先删除原有公告，新增一个新的公告，因此编辑后ID会变)")
    @PostMapping("/editNotice")
    public Result<?> editNotice(@Valid @RequestBody EditNoticeInVo inVo) {
        //删除原来的公告
        iNoticeService.getBaseMapper().deleteById(inVo.getId());
        //新增公告
        AddNoticeInVo notice = new AddNoticeInVo();
        BeanUtils.copyProperties(inVo, notice);
        String msg = iNoticeService.add(notice);
        return Result.success(msg);
    }

    @ApiOperation("获取公告列表")
    @GetMapping("/list")
    public Result<PageResult<NoticeListOutVo>> list(NoticeListInVo inVo,
                                                    @RequestParam(value = "pageNo") Long pageNo,
                                                    @RequestParam(value = "pageSize") Long pageSize){
        IPage<NoticeListOutVo> iPage = iNoticeService.getList(inVo, pageNo, pageSize);
        return Result.success(PageResult.valueOf(iPage));
    }

    @ApiOperation("获取公告详情")
    @GetMapping("/detail")
    public Result<NoticeDetailOutVo> detail(@RequestParam Integer id){
        Notice notice = iNoticeService.getById(id);
        if(notice == null){
            return Result.fail("获取失败，未查询到该公告！");
        }
        NoticeDetailOutVo outVo = new NoticeDetailOutVo();
        BeanUtils.copyProperties(notice, outVo, NoticeDetailOutVo.class);
        return Result.success(outVo);
    }

}
